package com.hispot.download;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import java.io.File;
import java.security.MessageDigest;

/**
 * Created by ASUS-PC on 2016/11/13.
 */

public class FileDownloadUtils {

    private static final String TAG = "FileDownloadUtils";

    public static boolean checkDirExistsAndCreate(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return file.mkdir();
        }
        return true;
    }

    public synchronized static boolean upDateDatabase(FileDownloadSQLiteHelper sqLiteHelper, String downloadUrl, long startPoint, long total, int downloadStatus) {
        return upDateDatabase(sqLiteHelper, downloadUrl, startPoint, total, downloadStatus, 0);
    }

    public synchronized static boolean upDateDatabase(FileDownloadSQLiteHelper sqLiteHelper, String downloadUrl, long startPoint, long total, int downloadStatus, int saveCount) {

        if (saveCount > 0) {
            int percent = (int) ((double) startPoint / total * 100);
            int round = percent % (100 / saveCount);
            if (round != 0) return false;
        }

        SQLiteDatabase writableDatabase = sqLiteHelper.getWritableDatabase();

        Cursor query = writableDatabase.query(FileDownloadConstant.TABLE_NAME, null, FileDownloadConstant.DOWNLOAD_URL + " like ?", new String[]{downloadUrl}, null, null, null);

        ContentValues values = new ContentValues();
        values.put(FileDownloadConstant.START_POINT, startPoint);
        values.put(FileDownloadConstant.DOWNLOAD_URL, downloadUrl);
        values.put(FileDownloadConstant.DOWNLOAD_STATUS, downloadStatus);
        values.put(FileDownloadConstant.TOTAL, total);

        if (query != null && !query.isClosed() && query.moveToFirst()) {
            query.close();
            if (!writableDatabase.isOpen()) return false;
            writableDatabase.update(FileDownloadConstant.TABLE_NAME, values, FileDownloadConstant.DOWNLOAD_URL + " like ?", new String[]{downloadUrl});
        } else {
            if (!writableDatabase.isOpen()) return false;
            writableDatabase.insert(FileDownloadConstant.TABLE_NAME, null, values);
        }

        return true;
    }

    public synchronized static long getStartPoint(FileDownloadSQLiteHelper sqLiteHelper, String downloadUrl) {
        SQLiteDatabase readableDatabase = sqLiteHelper.getReadableDatabase();

        if (!readableDatabase.isOpen()) return 0;

        Cursor query = readableDatabase.query(FileDownloadConstant.TABLE_NAME, null, FileDownloadConstant.DOWNLOAD_URL + " like ?", new String[]{downloadUrl}, null, null, null);

        long startPoint = 0;

        if (query != null && !query.isClosed() && query.moveToFirst()) {
            startPoint = query.getLong(query.getColumnIndex(FileDownloadConstant.START_POINT));
            query.close();
        }

        return startPoint;
    }

    public synchronized static FileDownloadModel getFileDownloadStatus(FileDownloadSQLiteHelper sqLiteHelper, String downloadUrl) {
        SQLiteDatabase readableDatabase = sqLiteHelper.getReadableDatabase();

        FileDownloadModel model = new FileDownloadModel();
        model.downloadUrl = downloadUrl;

        if (!readableDatabase.isOpen()) return model;

        Cursor query = readableDatabase.query(FileDownloadConstant.TABLE_NAME, null, FileDownloadConstant.DOWNLOAD_URL + " like ?", new String[]{downloadUrl}, null, null, null);

        if (query != null && !query.isClosed() && query.moveToFirst()) {
            model.soFar = query.getLong(query.getColumnIndex(FileDownloadConstant.START_POINT));
            model.total = query.getLong(query.getColumnIndex(FileDownloadConstant.TOTAL));
            model.status = query.getInt(query.getColumnIndex(FileDownloadConstant.DOWNLOAD_STATUS));

            model.percent = (int) ((double) model.soFar / model.total * 100);

            query.close();
        }

        return model;
    }

    public static long checkPoint(long startPoint, String path) {
        File file = new File(path);
        if (startPoint != file.length()) {
            startPoint = 0;
            boolean delete = file.delete();
            Log.e(TAG, "checkPoint: isDelete="+delete);
        }
        return startPoint;
    }

    public static String parseMD5(String plainText) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            return buf.toString().substring(8, 24);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
